<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑课件笔记' : '添加课件笔记' }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option :key="1" label="课件" :value="1" />
            <el-option :key="2" label="笔记" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="教育阶段" prop="educationLevel">
          <el-select v-model="form.educationLevel" placeholder="请选择教育阶段" @change="handleEducationLevelChange">
            <el-option :key="1" label="小学" :value="1" />
            <el-option :key="2" label="初中" :value="2" />
            <el-option :key="3" label="高中" :value="3" />
            <el-option :key="4" label="大学" :value="4" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="学科" prop="subjectId">
          <el-select v-model="form.subjectId" placeholder="请选择学科" filterable>
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="学校" prop="schoolId">
          <el-select v-model="form.schoolId" placeholder="请选择学校（不选则所有学校可见）" filterable clearable>
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="封面图">
          <el-upload
            class="cover-uploader"
            action="#"
            :http-request="uploadCover"
            :show-file-list="false"
            :before-upload="beforeCoverUpload"
          >
            <img v-if="form.coverUrl" :src="form.coverUrl" class="cover">
            <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">建议上传16:9比例图片，大小不超过2MB</div>
        </el-form-item>
        
        <el-form-item label="文件" v-if="form.type === 1">
          <el-upload
            class="file-uploader"
            action="#"
            :http-request="uploadFile"
            :before-upload="beforeFileUpload"
            :file-list="fileList"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持PDF、PPT、PPTX、DOC、DOCX格式，大小不超过50MB</div>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <div class="editor-container">
            <quill-editor
              v-model="form.content"
              ref="quillEditor"
              :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @ready="onEditorReady($event)"
            />
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getMaterialDetail, addMaterial, updateMaterial } from '@/api/material';
import { uploadFile as uploadFileAPI, uploadCover as uploadCoverAPI } from '@/api/material';
import { getAllSubjects } from '@/api/subject';
import { getSchoolList } from '@/api/school';
import { quillEditor } from 'vue-quill-editor';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';

export default {
  name: 'MaterialEdit',
  components: {
    quillEditor
  },
  data() {
    return {
      form: {
        id: undefined,
        title: '',
        content: '',
        type: 1,
        fileUrl: '',
        coverUrl: '',
        educationLevel: undefined,
        subjectId: undefined,
        schoolId: undefined,
        userId: this.$store.getters.userInfo.id
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        educationLevel: [{ required: true, message: '请选择教育阶段', trigger: 'change' }],
        subjectId: [{ required: true, message: '请选择学科', trigger: 'change' }]
      },
      loading: false,
      isEdit: false,
      subjectOptions: [],
      schoolOptions: [],
      fileList: [],
      allSubjects: [],
      editorOption: {
        placeholder: '请输入内容...',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }],
            [{ 'indent': '-1' }, { 'indent': '+1' }],
            [{ 'direction': 'rtl' }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'font': [] }],
            [{ 'align': [] }],
            ['clean'],
            ['link', 'image', 'video']
          ]
        }
      }
    };
  },
  created() {
    this.getSchools();
    this.getSubjects();
    
    if (this.$route.params && this.$route.params.id) {
      this.isEdit = true;
      this.fetchData(this.$route.params.id);
    }
  },
  methods: {
    fetchData(id) {
      this.loading = true;
      getMaterialDetail(id)
        .then(response => {
          this.form = response.data;
          
          // 如果有文件，添加到文件列表
          if (this.form.fileUrl) {
            this.fileList = [{
              name: this.form.title,
              url: this.form.fileUrl
            }];
          }
          
          this.loading = false;
          
          // 根据教育阶段筛选学科
          this.filterSubjectsByLevel(this.form.educationLevel);
        })
        .catch(() => {
          this.loading = false;
          this.$message.error('获取课件笔记信息失败');
          this.goBack();
        });
    },
    getSubjects() {
      getAllSubjects()
        .then(response => {
          this.allSubjects = response.data;
          if (this.form.educationLevel) {
            this.filterSubjectsByLevel(this.form.educationLevel);
          }
        })
        .catch(() => {
          this.$message.error('获取学科列表失败');
        });
    },
    getSchools() {
      getSchoolList(1, 100) // 获取第1页，最多100个学校
        .then(response => {
          const schools = response.data.records;
          this.schoolOptions = schools.map(school => ({
            value: school.id,
            label: school.name
          }));
        })
        .catch(() => {
          this.$message.error('获取学校列表失败');
        });
    },
    handleEducationLevelChange(level) {
      this.filterSubjectsByLevel(level);
      // 清空已选学科
      this.form.subjectId = undefined;
    },
    filterSubjectsByLevel(level) {
      if (!level || !this.allSubjects || this.allSubjects.length === 0) return;
      
      const filteredSubjects = this.allSubjects.filter(subject => subject.level === level);
      this.subjectOptions = filteredSubjects.map(subject => ({
        value: subject.id,
        label: subject.name
      }));
    },
    beforeCoverUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('封面图片只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('封面图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    uploadCover(options) {
      const { file } = options;
      this.loading = true;
      uploadCoverAPI(file)
        .then(response => {
          this.form.coverUrl = response.data.url;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.$message.error('上传封面图片失败');
        });
    },
    beforeFileUpload(file) {
      const validTypes = ['application/pdf', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
      const isValidType = validTypes.includes(file.type);
      const isLt50M = file.size / 1024 / 1024 < 50;

      if (!isValidType) {
        this.$message.error('只能上传PDF、PPT、PPTX、DOC、DOCX格式文件!');
      }
      if (!isLt50M) {
        this.$message.error('文件大小不能超过 50MB!');
      }
      return isValidType && isLt50M;
    },
    uploadFile(options) {
      const { file } = options;
      this.loading = true;
      uploadFileAPI(file)
        .then(response => {
          this.form.fileUrl = response.data.url;
          this.loading = false;
          this.fileList = [{
            name: file.name,
            url: response.data.url
          }];
        })
        .catch(() => {
          this.loading = false;
          this.$message.error('上传文件失败');
        });
    },
    onEditorBlur() {
      // 编辑器失去焦点时的回调
    },
    onEditorFocus() {
      // 编辑器获得焦点时的回调
    },
    onEditorReady() {
      // 编辑器准备好时的回调
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 如果是课件类型，必须上传文件
          if (this.form.type === 1 && !this.form.fileUrl) {
            this.$message.error('请上传课件文件');
            return;
          }
          
          this.loading = true;
          const request = this.isEdit ? updateMaterial(this.form) : addMaterial(this.form);
          request
            .then(() => {
              this.$message({
                message: this.isEdit ? '更新成功' : '创建成功',
                type: 'success'
              });
              this.loading = false;
              this.goBack();
            })
            .catch(() => {
              this.loading = false;
              this.$message({
                message: this.isEdit ? '更新失败' : '创建失败',
                type: 'error'
              });
            });
        }
      });
    },
    goBack() {
      this.$router.push('/materials');
    }
  }
};
</script>

<style scoped>
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader .el-upload:hover {
  border-color: #409EFF;
}
.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.cover {
  width: 178px;
  height: 100px;
  display: block;
  object-fit: cover;
}
.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}
.editor-container {
  min-height: 300px;
  margin-bottom: 30px;
}
.quill-editor {
  height: 300px;
}
</style>